import store from '@/store'
import { isLogin } from '@/utils'
import axios from 'axios'
import Vue from 'vue'
import VueRouter from 'vue-router'
import layout from '@/views/layouts/index.vue'

import NotFound from '@/views/featrue/404.vue'
import Privilege from '@/views/featrue/401.vue'
Vue.use(VueRouter)
// 处理路由跳转的异常提示: 功能上没有问题的, 要么换3.0版本, 要么catch一下不处理不报错
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch((error) => error)
}
const routes = [
  {
    path: '/',
    redirect: '/dashboard',
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue'),
  },
  { name: 'notFound', path: '/404', component: NotFound },
  { name: 'privilege', path: '/401', component: Privilege },
]
function convertRole(id) {
  switch (id) {
    case 1:
      return '审批专员'
    case 2:
      return '录入专员'
    case 3:
      return '管理员'
  }
}
const router = new VueRouter({
  routes,
})
function asyncRoutesHandler(routes) {
  return routes.map((route) => {
    if (route.component === 'Layout') {
      route.component = layout // Layout
    } else {
      // 子路由
      const filePath = route.component
      route.component = () => import(`../views/${filePath}.vue`)
    }
    if (route.children) {
      route.children = asyncRoutesHandler(route.children)
    }
    return route
  })
}
function loadAsyncRoutes() {
  return axios.get('/menus.json')
}
// 加载菜单
async function loadMenu(to, from, next) {
  // 异步请求
  let res = await loadAsyncRoutes()
  store.commit('user/setMenu', res.data)

  // 加载菜单
  const asyncRoutes = asyncRoutesHandler(res.data)

  asyncRoutes.forEach((r) => {
    // 动态添加路由
    router.addRoute(r)
  })

  router.addRoute({
    path: '*',
    redirect: { name: 'notFound' },
  })

  // 触发新的路由访问
  next({ ...to, repalce: true })
}
window.arr = []
const whiteList = ['/login']
router.beforeEach((to, from, next) => {
  window.arr.push(to.fullPath)
  // 不next() 一般就是白屏

  // 1. 验证是否是白名单（不需要登录也能访问的页面）
  if (whiteList.includes(to.path)) return next()

  // 2、需要判断是否登录
  // console.log(isLogin(),'isLogin()');
  let userData = isLogin()
  if (!userData) {
    console.log(to.hash, to.fullPath)
    let lastPath = to.fullPath // /abc
    return next({ name: 'login', query: { redirect: lastPath } })
  }
  let roleName = convertRole(userData.type)
  // console.log(roleName,'未来保存到vuex的角色名:');
  store.commit('user/changeUserInfo', {
    roleName,
  })
  store.commit('user/changeLogin', true)
  // 但是在登录之前已经加载过路由
  if (store.getters['user/userMenu'].length === 0) {
    return loadMenu(to, from, next) // 待加载菜单
  }
  // 但是在登录之前已经加载过路由
  // 已经有路由菜单,放行到login
  store.commit('user/changeDefaultActive',to.path)
  // 记录路由访问
  if (to?.meta?.title)
    store.commit('user/addCache', {
      name: to.name,// 组件名称
      title: to.meta.title,
    })

  next()
  // if (userData) {
  //   let roleName = convertRole(userData.type)
  //   // console.log(roleName,'未来保存到vuex的角色名:');
  //   store.commit('user/changeUserInfo', {
  //     roleName,
  //   })
  //   store.commit('user/changeLogin', true)
  //   // 但是在登录之前已经加载过路由
  //   if (store.getters['user/userMenu'].length > 0) {
  //     // 肯定进不来
  //     // 已经有路由菜单,放行到login
  //     return next()
  //   } else {
  //     // 待加载菜单
  //     return loadMenu(to, from, next)
  //   }
  //   // return next();
  // } else {
  //   console.log(to.hash, to.fullPath)
  //   let lastPath = to.fullPath // /abc
  //   return next({ name: 'login', query: { redirect: lastPath } })
  // }
  // // debugger;
  // alert('不允许访问')
  // next(false);
})
export default router
